package com.mark.jpa.service.impl;

import com.mark.jpa.entity.Employee;
import com.mark.jpa.service.EmployeeDAO;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;

@Transactional
@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
    @PersistenceContext
    EntityManager em;
 
 
    @Override
    public void save(Employee employee) {
        em.persist(employee);
    }
 
    @Override
    public Employee getById(int id) {
        return em.find(Employee.class, id);
    }
 
    public void update(Employee employee) {  
        em.merge(employee);
    }
 
    @Override
    public void deleteById(int id) {
        em.remove(this.getById(id));
    }
 
    @Override
    public List<Employee> getAll() {
        CriteriaBuilder builder =em.getCriteriaBuilder();
        final CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
        return this.em.createQuery(query).getResultList();
    }
}